package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Product;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Trace;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.LoginServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.ProductServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.LoginService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.ProductService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.ImageUtils;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.JSONObjectUtils;

public class ActivityVerification extends AppCompatActivity {

    private EditText mProductId, mProductName, mProductType, mProductPrice, mProductDate, mDealerDate, mConsumerDate, mProductState;
    private EditText tProducerId, tDealerId, tConsumerId;
    private ImageView iProducer, iDealer, iConsumer;

    private EditText etVerificationCode;
    private Button btnVerify,btnBack;
    private LinearLayout llProductInfo;
    private ImageView ivMailIcon;
    private TextView tvMailCount;
    private int verificationCode;  // 存储验证码
    private ProductServiceConnection productConnection;
    private Product product;
    private Trace trace;
    private SharedPreferences sharedPreferencesUser;

    @Override
    protected void onStart() {
        super.onStart();

        productConnection = new ProductServiceConnection(service -> {
            service.requestTraceability(sharedPreferencesUser.getInt("userId",-1),"1234567890");
        });
        Intent intent = new Intent(this, ProductService.class);
        bindService(intent, productConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (productConnection.isBound()) {
            unbindService(productConnection);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification);

        etVerificationCode = findViewById(R.id.et_verification_code);
        btnVerify = findViewById(R.id.btn_verify);
        btnBack = findViewById(R.id.btn_back);
        ivMailIcon = findViewById(R.id.iv_mail_icon);
        tvMailCount = findViewById(R.id.tv_mail_count);


        sharedPreferencesUser = getSharedPreferences("ACCOUNT_REMEMBER", MODE_PRIVATE);
        int userId = sharedPreferencesUser.getInt("userId",-1);
        // 获取并显示存储的验证码
        SharedPreferences sharedPreferences = getSharedPreferences("SmsData", MODE_PRIVATE);
        String productId = sharedPreferences.getString("productId", "");
        String message = sharedPreferences.getString("message", "");
        String[] parts = message.split("：");
        if (parts.length > 1) {
            verificationCode = Integer.parseInt(parts[1].split("，")[0]); // 提取验证码
        }

        // 返回
        btnBack.setOnClickListener(v ->{finish();});

        // 监听验证按钮
        btnVerify.setOnClickListener(v -> {
            String inputCode = etVerificationCode.getText().toString();
            JSONObject result = productConnection.getService().verifyTraceability(userId,productId,inputCode);
            try {
                boolean success = result.getBoolean("success");
                if (success) {
                    Product resultProduct = JSONObjectUtils.getProduct(result);
                    Trace resultTrace = JSONObjectUtils.getTrace(result);
                    product = resultProduct;
                    trace = resultTrace;
                    showProductInfo();
                } else {
                    String message1 = JSONObjectUtils.getMessage(result);
                    Toast.makeText(this,"验证码错误！",Toast.LENGTH_SHORT);
                    Log.d("ProductInfo2",message1);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        });

        // 右上角信箱点击事件
        ivMailIcon.setOnClickListener(v -> showMailPopup());
    }

    private void showProductInfo() {
        // 检查服务是否已绑定，确保可以调用服务
        if (productConnection.isBound()) {
            fillProductInfo(product,trace);
        } else {
            Toast.makeText(this, "服务未绑定，请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("SetTextI18n")
    private void fillProductInfo(Product product,Trace trace) {
        Log.d("ProductInfo1",trace.toString());
        // 获取布局中的TextView元素
        mProductId = findViewById(R.id.product_id_value);
        mProductName = findViewById(R.id.product_name_value);
        mProductType = findViewById(R.id.product_type_value);
        mProductPrice = findViewById(R.id.product_price_value);
        mProductDate = findViewById(R.id.produce_date_value);
        mDealerDate = findViewById(R.id.manufacture_date_value);
        mConsumerDate = findViewById(R.id.sale_date_value);

        tProducerId = findViewById(R.id.producer_id_value);
        iProducer = findViewById(R.id.producer_img_value);
        tDealerId = findViewById(R.id.dealer_id_value);
        iDealer = findViewById(R.id.dealer_img_value);
        tConsumerId = findViewById(R.id.consumer_id_value);
        iConsumer = findViewById(R.id.consumer_img_value);

        mProductId.setText(product.getProductId());
        mProductName.setText(product.getProductName());
        mProductType.setText(product.getCategory());
        mProductPrice.setText(product.getPrice().toString());
        mProductDate.setText(product.getProduceDate());
        mDealerDate.setText(product.getManufactureDate());
        mConsumerDate.setText(product.getSellDate());

        tProducerId.setText(trace.getProducerId().toString());
        if (trace.getProducerImg() != null){
            iProducer.setImageBitmap(ImageUtils.blob2Bitmap(trace.getProducerImg()));
        }
        tDealerId.setText(trace.getDealerId().toString());
        if (trace.getDealerImg() != null){
            iDealer.setImageBitmap(ImageUtils.blob2Bitmap(trace.getDealerImg()));
        }
        tConsumerId.setText(trace.getConsumerId().toString());
        if (trace.getConsumerImg() != null){
            iConsumer.setImageBitmap(ImageUtils.blob2Bitmap(trace.getConsumerImg()));
        }


    }


    private void showMailPopup() {
        // 显示验证码的弹窗
        SharedPreferences sharedPreferences = getSharedPreferences("SmsData", MODE_PRIVATE);
        String message = sharedPreferences.getString("message", "");
        if (tvMailCount.getVisibility() == View.GONE) {
            tvMailCount.setVisibility(View.VISIBLE);  // 显示 TextView
        } else {
            tvMailCount.setVisibility(View.GONE);  // 隐藏 TextView
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("验证码信息")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }

    public void updateMailCount(int count) {
        if (count > 0) {
            tvMailCount.setVisibility(View.VISIBLE);
            tvMailCount.setText(String.valueOf(count));  // 设置显示的短信数量
        } else {
            tvMailCount.setVisibility(View.GONE);  // 如果没有收到短信，则隐藏
        }
    }
}




